import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import json.JSONObject;

public class NewAjaxServer extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		this.doGet(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html;charset=utf-8");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		System.out.println("startTime=" + startTime);
		System.out.println("endTime=" + endTime);

		//得到当前页数
		String page = request.getParameter("page");
		//得到每页显示行数
		String maxResult = request.getParameter("rp");

		String sortname = request.getParameter("sortname");
		String query = request.getParameter("query");
		String qtype = request.getParameter("qtype");

		//计算查询开始数据下标
		int startIndex = (Integer.parseInt(page) - 1) * Integer.parseInt(maxResult);
		Map pageInfo = new HashMap();
		//当前页数设置
		pageInfo.put("page", page);
		//总数据量设置
		pageInfo.put("total", 100);

		String jsonStr = getJsonString(startIndex, Integer.parseInt(maxResult), pageInfo);
		System.out.println(jsonStr);
		//response 相关处理
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		try {
			response.getWriter().write(jsonStr);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getJsonString(int startIndex, int maxResult, Map pageInfo) {
		List mapList = new ArrayList();
		for (int i = startIndex; i < startIndex + maxResult; i++) {
			Map cellMap = new HashMap();
			cellMap.put("id", i);
			cellMap.put("cell", new Object[] { "keyword" + i, "sessionDuration" + i, "pageView" + i, "registrations" + i, "numberOfOrder" + i,
					"orderExtRetail" + i, "impression" + i, "click" + i, "cost" + i, "ctr" + i, "cpc" + i, "roas" + i, "epg" + i, "revPerOrder" + i });
			mapList.add(cellMap);
		}
		pageInfo.put("rows", mapList);
		JSONObject object = new JSONObject(pageInfo);
		return object.toString();
	}
}